// API service for administrative tasks
import axios from 'axios';

class AdminService {
  /**
   * Get pet reaction configs
   * @returns {Promise<Object>} API response
   */
  static async getPetReactionConfigs() {
    try {
      const response = await axios.get('/api/admin/pet-reaction-configs');

      // If the response data is an array, handle it directly.
      if (response.data && Array.isArray(response.data)) {
        return {
          success: true,
          data: response.data,
          message: '获取成功'
        };
      }

      // Handle object-wrapped responses, like { code: 200, data: [...] }
      if (response.data && response.data.code === 200) {
        return {
          success: true,
          data: response.data.data || [],
          message: response.data.message || '获取成功'
        };
      } else {
        return {
          success: false,
          message: response.data?.message || '获取配置失败'
        };
      }
    } catch (error) {
      console.error('获取宠物反应配置失败:', error);
      // Using a generic error handler similar to other services
      if (error.response) {
        return {
          success: false,
          message: `获取配置失败: ${error.response.data?.message || '服务器错误'} (状态码: ${error.response.status})`
        };
      } else if (error.request) {
        return {
          success: false,
          message: '请求超时，请检查网络连接'
        };
      } else {
        return {
          success: false,
          message: '请求失败: ' + (error.message || '未知错误')
        };
      }
    }
  }

  /**
   * Update a pet reaction config by ID
   * @param {number} id - The ID of the reaction config to update
   * @param {Object} payload - The update payload
   * @returns {Promise<Object>} API response
   */
  static async updatePetReactionConfig(id, payload) {
    try {
      const response = await axios.put(`/api/admin/pet-reaction-configs/${id}`, payload);
      if (response.status === 200) {
        return {
          success: true,
          message: '更新成功'
        };
      } else {
        return {
          success: false,
          message: response.data?.message || '更新失败'
        };
      }
    } catch (error) {
      console.error(`更新宠物反应配置 (ID: ${id}) 失败:`, error);
      if (error.response) {
        return {
          success: false,
          message: `更新配置失败: ${error.response.data?.message || '服务器错误'} (状态码: ${error.response.status})`
        };
      } else if (error.request) {
        return {
          success: false,
          message: '请求超时，请检查网络连接'
        };
      } else {
        return {
          success: false,
          message: '请求失败: ' + (error.message || '未知错误')
        };
      }
    }
  }

  /**
   * Get all reward rules
   * @returns {Promise<Object>} API response
   */
  static async getAllRewards() {
    try {
      const response = await axios.get('/api/admin/rewards');
      if (response.data && Array.isArray(response.data)) {
        return {
          success: true,
          data: response.data,
          message: '获取成功'
        };
      }
      if (response.data && response.data.code === 200) {
        return {
          success: true,
          data: response.data.data || [],
          message: response.data.message || '获取成功'
        };
      } else {
        return {
          success: false,
          message: response.data?.message || '获取奖励规则失败'
        };
      }
    } catch (error) {
      console.error('获取奖励规则失败:', error);
      if (error.response) {
        return {
          success: false,
          message: `获取奖励规则失败: ${error.response.data?.message || '服务器错误'} (状态码: ${error.response.status})`
        };
      } else if (error.request) {
        return {
          success: false,
          message: '请求超时，请检查网络连接'
        };
      } else {
        return {
          success: false,
          message: '请求失败: ' + (error.message || '未知错误')
        };
      }
    }
  }

  /**
   * Update an existing reward rule by ID
   * @param {number} ruleId - The ID of the reward rule to update
   * @param {Object} payload - The update payload
   * @returns {Promise<Object>} API response
   */
  static async updateReward(ruleId, payload) {
    try {
      const response = await axios.put(`/api/admin/rewards/${ruleId}`, payload);
      if (response.status === 200) {
        return {
          success: true,
          data: response.data, // 返回更新后的完整规则对象
          message: '更新成功'
        };
      } else {
        return {
          success: false,
          message: response.data?.message || '更新失败'
        };
      }
    } catch (error) {
      console.error(`更新奖励规则 (ID: ${ruleId}) 失败:`, error);
      if (error.response) {
        return {
          success: false,
          message: `更新奖励规则失败: ${error.response.data?.message || '服务器错误'} (状态码: ${error.response.status})`
        };
      } else if (error.request) {
        return {
          success: false,
          message: '请求超时，请检查网络连接'
        };
      } else {
        return {
          success: false,
          message: '请求失败: ' + (error.message || '未知错误')
        };
      }
    }
  }
  /**
   * Create a new pet reaction config
   * @param {Object} payload - The new config data
   * @returns {Promise<Object>} API response
   */
  static async createPetReactionConfig(payload) {
    try {
      const response = await axios.post('/api/admin/pet-reaction-configs', payload);
      if (response.status === 201 || response.status === 200) {
        return {
          success: true,
          data: response.data,
          message: '创建成功'
        };
      } else {
        return {
          success: false,
          message: response.data?.message || '创建失败'
        };
      }
    } catch (error) {
      console.error('创建宠物反应配置失败:', error);
      if (error.response) {
        return {
          success: false,
          message: `创建配置失败: ${error.response.data?.message || '服务器错误'} (状态码: ${error.response.status})`
        };
      } else if (error.request) {
        return {
          success: false,
          message: '请求超时，请检查网络连接'
        };
      } else {
        return {
          success: false,
          message: '请求失败: ' + (error.message || '未知错误')
        };
      }
    }
  }

  /**
   * Delete a pet reaction config by ID
   * @param {number} id - The ID of the reaction config to delete
   * @returns {Promise<Object>} API response
   */
  static async deletePetReactionConfig(id) {
    try {
      const response = await axios.delete(`/api/admin/pet-reaction-configs/${id}`);
      if (response.status === 200 || response.status === 204) {
        return {
          success: true,
          message: '删除成功'
        };
      } else {
        return {
          success: false,
          message: response.data?.message || '删除失败'
        };
      }
    } catch (error) {
      console.error(`删除宠物反应配置 (ID: ${id}) 失败:`, error);
      if (error.response) {
        return {
          success: false,
          message: `删除配置失败: ${error.response.data?.message || '服务器错误'} (状态码: ${error.response.status})`
        };
      } else if (error.request) {
        return {
          success: false,
          message: '请求超时，请检查网络连接'
        };
      } else {
        return {
          success: false,
          message: '请求失败: ' + (error.message || '未知错误')
        };
      }
    }
  }

  /**
   * Get all users
   * @returns {Promise<Object>} API response
   */
  static async getAllUsers() {
    try {
      const response = await axios.get('/api/admin/users');
      if (response.data && Array.isArray(response.data)) {
        return {
          success: true,
          data: response.data,
          message: '获取成功'
        };
      }
      if (response.data && response.data.code === 200) {
        return {
          success: true,
          data: response.data.data || [],
          message: response.data.message || '获取成功'
        };
      } else {
        return {
          success: false,
          message: response.data?.message || '获取用户列表失败'
        };
      }
    } catch (error) {
      console.error('获取用户列表失败:', error);
      if (error.response) {
        return {
          success: false,
          message: `获取用户列表失败: ${error.response.data?.message || '服务器错误'} (状态码: ${error.response.status})`
        };
      } else if (error.request) {
        return {
          success: false,
          message: '请求超时，请检查网络连接'
        };
      } else {
        return {
          success: false,
          message: '请求失败: ' + (error.message || '未知错误')
        };
      }
    }
  }

  /**
   * Give items to a user
   * @param {Object} payload - The item and quantity to give to the user
   * @param {number} payload.userId - The ID of the user
   * @param {string} payload.itemId - The ID of the item
   * @param {number} payload.quantity - The quantity of the item
   * @returns {Promise<Object>} API response
   */
  static async giveItemToUser(payload) {
    try {
      const response = await axios.post('/api/admin/users/items', payload);
      if (response.status === 200 || response.status === 201) {
        return {
          success: true,
          data: response.data,
          message: '物品添加成功'
        };
      } else {
        return {
          success: false,
          message: response.data?.message || '添加物品失败'
        };
      }
    } catch (error) {
      console.error('添加物品失败:', error);
      if (error.response) {
        return {
          success: false,
          message: `添加物品失败: ${error.response.data?.message || '服务器错误'} (状态码: ${error.response.status})`
        };
      } else if (error.request) {
        return {
          success: false,
          message: '请求超时，请检查网络连接'
        };
      } else {
        return {
          success: false,
          message: '请求失败: ' + (error.message || '未知错误')
        };
      }
    }
  }
}

export const { 
  getPetReactionConfigs, 
  updatePetReactionConfig, 
  getAllRewards, 
  updateReward,
  createPetReactionConfig,
  deletePetReactionConfig,
  getAllUsers, // New: Export getAllUsers
  giveItemToUser // New: Export giveItemToUser
} = AdminService;
export default AdminService;
